import { FC, useEffect } from 'react'
import { Modal, Form, Input } from 'antd'
import axios from 'axios'

interface IProps {
    id?: string
    visible: boolean
    onClose: () => void
    onSucess: () => void
}

const AddModal: FC<IProps> = ({ id, visible, onClose, onSucess }) => {
    const [form] = Form.useForm();

    useEffect(() => {
        if (id) {
            axios.get(`http://127.0.0.1:8000/goods/detail/${id}`)
                .then(data => {
                    console.log(data)
                    form.setFieldsValue({
                        ...data.data
                    })
                })
                .catch(error => {
                    console.error("There was an error fetching the items!", error);
                });
        }
    }, [form, id])

    const onOk = () => {
        form.submit()
    }

    const handleSubmit = (data: unknown) => {
        if (id) {
            axios.put(`http://127.0.0.1:8000/goods/detail/${id}`, data)
                .then(() => {
                    onSucess()
                    onClose()
                })
                .catch(error => {
                    console.error("There was an error fetching the items!", error);
                });
        } else {
            axios.post(`http://127.0.0.1:8000/goods/list`, data)
                .then(() => {
                    onSucess()
                    onClose()
                })
                .catch(error => {
                    console.error("There was an error fetching the items!", error);
                });
        }
    }

    return <Modal open={visible} onClose={onClose} onOk={onOk}>
        <Form
            form={form}
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            autoComplete="off"
            onFinish={handleSubmit}
        >
            <Form.Item
                label="名称"
                name="name"
                required>
                <Input />
            </Form.Item>

            <Form.Item
                label="价格"
                name="price"
                required
            >
                <Input />
            </Form.Item>
            <Form.Item
                label="描述"
                name="description"
                required
            >
                <Input.TextArea />
            </Form.Item>
        </Form>
    </Modal>
}

export default AddModal